package com.example.zhengsqdemo.weight

import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.example.onlineeducation.R
import com.example.onlineeducation.widget.video.LandLayoutVideo
import com.google.android.exoplayer2.SeekParameters
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.Debuger
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager

class VideoUtil @JvmOverloads constructor(
    var mActivity: FragmentActivity,
    mLifecycleOwner: LifecycleOwner,
    var mDetailPlayer: LandLayoutVideo
) {
    private var isPlay = false

    private var isPause = false

    private var isTile = View.GONE

    private lateinit var mGsyVideoOption: GSYVideoOptionBuilder
    private lateinit var orientationUtils: OrientationUtils

    init {
        mLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onResume(owner: LifecycleOwner) {
                getCurPlay().onVideoResume(false)
                isPause = false
                super.onResume(owner)
            }

            override fun onPause(owner: LifecycleOwner) {
                getCurPlay().onVideoPause()
                isPause = true
                super.onPause(owner)
            }

            override fun onDestroy(owner: LifecycleOwner) {
                if (isPlay) {
                    getCurPlay().release()
                }
                if (orientationUtils != null) orientationUtils.releaseListener()
                super.onDestroy(owner)
            }
        })

        resolveNormalVideoUI(isTile)

        //外部辅助的旋转，帮助全屏
        orientationUtils = OrientationUtils(mActivity, mDetailPlayer)
        //初始化不打开外部的旋转
        orientationUtils.isEnable = false

        initConfig()

    }

    fun setUrl(url: String): VideoUtil {
        getCurPlay().release()
        mGsyVideoOption
            .setUrl(url)
            .build(mDetailPlayer)
        return this
    }

    fun closeVideo() {
        getCurPlay().release()
    }

    fun backFullToBackPressed(): Boolean {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo()
        }
        return GSYVideoManager.backFromWindowFull(mActivity)
    }

    private fun getCurPlay(): GSYVideoPlayer {
        return if (mDetailPlayer.fullWindowPlayer != null) {
            mDetailPlayer.fullWindowPlayer
        } else mDetailPlayer
    }

    private fun resolveNormalVideoUI(visibility: Int) {
        //增加title
        mDetailPlayer.titleTextView.visibility = visibility
        mDetailPlayer.backButton.visibility = visibility
    }

    private fun initConfig() {
        val header: MutableMap<String, String> = HashMap()
        header["ee"] = "33"
        header["allowCrossProtocolRedirects"] = "true"
        header["User-Agent"] = "GSY"
        mGsyVideoOption = GSYVideoOptionBuilder()
        mGsyVideoOption
            //.setThumbImageView(imageView)
            .setIsTouchWiget(true)
            .setRotateViewAuto(false) //仅仅横屏旋转，不变直
            //.setOnlyRotateLand(true)
            .setRotateWithSystem(false)
            .setLockLand(true)
            .setAutoFullWithSize(true)
            .setShowFullAnimation(false)
            .setNeedLockFull(true)
            // .setUrl("http://9890.vod.myqcloud.com/9890_4e292f9a3dd011e6b4078980237cc3d3.f20.mp4")
            .setMapHeadData(header)
            .setCacheWithPlay(false)
            .setSurfaceErrorPlay(false)
            .setVideoTitle("测试视频")
            .setVideoAllCallBack(object : GSYSampleCallBack() {
                override fun onPrepared(url: String, vararg objects: Any) {
                    Debuger.printfError("***** onPrepared **** " + objects[0])
                    Debuger.printfError("***** onPrepared **** " + objects[1])
                    super.onPrepared(url, *objects)
                    //开始播放了才能旋转和全屏
                    orientationUtils.isEnable = mDetailPlayer.isRotateWithSystem
                    isPlay = true
                    //设置 seek 的临近帧。
                    if (mDetailPlayer.gsyVideoManager
                            .player is Exo2PlayerManager
                    ) {
                        (mDetailPlayer.gsyVideoManager
                            .player as Exo2PlayerManager).setSeekParameter(SeekParameters.NEXT_SYNC)
                        Debuger.printfError("***** setSeekParameter **** ")
                    }
                }

                override fun onEnterFullscreen(url: String, vararg objects: Any) {
                    super.onEnterFullscreen(url, *objects)
                }

                override fun onAutoComplete(url: String, vararg objects: Any) {
                    super.onAutoComplete(url, *objects)
                }

                override fun onClickStartError(url: String, vararg objects: Any) {
                    super.onClickStartError(url, *objects)
                }

                override fun onQuitFullscreen(url: String, vararg objects: Any) {
                    super.onQuitFullscreen(url, *objects)

                    // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
                    // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
                    orientationUtils.backToProtVideo()
                    ImmersionBar.with(mActivity)
                        .statusBarColor(R.color.white)
                        .statusBarDarkFont(true)
                        .hideBar(BarHide.FLAG_SHOW_BAR)
                        .fullScreen(false)
                        .fitsSystemWindows(true)
                        .init()
                }
            })
            .setLockClickListener { view, lock ->
                orientationUtils.isEnable = !lock
            }
            .setGSYVideoProgressListener { progress, secProgress, currentPosition, duration ->

            }
            .build(mDetailPlayer)

        mDetailPlayer.fullscreenButton.setOnClickListener { //直接横屏
            // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
            // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
            ImmersionBar.with(mActivity)
                .statusBarColor(R.color.transparent)
                .statusBarDarkFont(false)
                .hideBar(BarHide.FLAG_SHOW_BAR)
                .fitsSystemWindows(false)
                .init()
            orientationUtils.resolveByClick()

            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
            mDetailPlayer.startWindowFullscreen(mActivity, true, true)
        }
    }
}